package cn.itcast.bos.web.action.bc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.bc.DecidedZone;
import cn.itcast.bos.domain.bc.Staff;
import cn.itcast.bos.domain.bc.customer.Customer;
import cn.itcast.bos.web.action.base.BaseAction;

@Controller("decidedZoneAction")
@Scope("prototype")
@Namespace("/bc")
@ParentPackage("bos")
public class DecidedZoneAction extends BaseAction<DecidedZone> {
	// 分区ids 如何获取
	private String[] ids;

	public void setIds(String[] ids) {
		this.ids = ids;
	}

	private String association;// 0/1 ""

	public void setAssociation(String association) {
		this.association = association;
	}

	// 接受 关联客户 所有id
	private Integer[] customerIds;

	public void setCustomerIds(Integer[] customerIds) {
		this.customerIds = customerIds;
	}

	// 关联客户 到定区
	@Action(value = "decidedZoneAction_associtionsCustomersToDecidedZone", results = { @Result(name = "associtionsCustomersToDecidedZone", location = "/WEB-INF/pages/base/decidedzone.jsp") })
	public String associtionsCustomersToDecidedZone() {
		try {
			customerService.assignCustomersToDecidedZone(customerIds, model.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "associtionsCustomersToDecidedZone";
	}

	@Action(value = "decidedZoneAction_addDecidedZone", results = { @Result(name = "addDecidedZone", location = "/WEB-INF/pages/base/decidedzone.jsp") })
	public String addDecidedZone() {
		// /业务层 获取 请求参数 执行定区添加 数据库更细两张 定区 id 分区 update 分区 ids 循环更新
		try {
			decidedZoneService.addDecidedZone(model, ids);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "addDecidedZone";
	}

	// 关联客户实现
	@Action(value = "decidedZoneAction_noassocitionsCustomers")
	public String noassocitionsCustomers() {
		List<Customer> noCustomers = customerService.findAllNoAssociationsCustomers();
		getValueStack().push(noCustomers);
		return SUCCESS;
	}

	// 关联客户实现
	@Action(value = "decidedZoneAction_hasassocitionsCustomers")
	public String hasassocitionsCustomers() {
		List<Customer> hasCustomers = customerService.findAllNoAssociationsCustomer(model.getId());
		getValueStack().push(hasCustomers);
		return SUCCESS;
	}

	// 条件查询
	@Action(value = "decidedZoneAction_ajaxList")
	public String ajaxList() {
		Map<String, Object> results = new HashMap<String, Object>();
		Pageable pageRequest = new PageRequest(page - 1, rows);
		Specification<DecidedZone> specification = getSpecifecation();
		Page<DecidedZone> pageData = decidedZoneService.findAll(pageRequest, specification); // model 分页条件参数---->Sepecification
		results.put("total", pageData.getTotalElements());// map 封装 easyui datagrid 插件需要数据格式 total 和 rows
		results.put("rows", pageData.getContent());
		getValueStack().push(results);
		return SUCCESS;
	}

	private Specification<DecidedZone> getSpecifecation() {
		Specification<DecidedZone> specification = new Specification<DecidedZone>() {
			public Predicate toPredicate(Root<DecidedZone> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> accordingList = new ArrayList<Predicate>();
				// 定区id 精确查询
				if (StringUtils.isNotBlank(model.getId())) {
					Predicate p1 = cb.equal(root.get("id").as(String.class), model.getId());
					accordingList.add(p1);
				}

				if (model.getStaff() != null) {
					Join<DecidedZone, Staff> staffJoin = root.join(root.getModel().getSingularAttribute("staff", Staff.class), JoinType.LEFT);
					if (StringUtils.isNotBlank(model.getStaff().getStation())) {
						Predicate p2 = cb.like(staffJoin.get("station").as(String.class), "%" + model.getStaff().getStation() + "%");
						accordingList.add(p2);
					}

				}
				// 2: 判断 下拉框是否为null
				// 用户输入 定区编码id --->oid 查询信息
				if (StringUtils.isNotBlank(association)) {
					Expression<Set> subareas = root.get("subareas").as(Set.class);// 定区关联分区
					if ("0".equals(association)) {
						// 没有关联分区
						// SetJoin<DecidedZone, Set> subAreajoin = root.join(root.getModel().getSet("subareas", Set.class),JoinType.LEFT);
						Predicate p3 = cb.isEmpty(subareas);
						accordingList.add(p3);
					} else if ("1".equals(association)) {
						Predicate p4 = cb.isNotEmpty(subareas);
						accordingList.add(p4);
					}

				}

				/**
				 * Predicate[] p = new Predicate[list.size()]; return cb.and(list.toArray(p));
				 */
				// 条件s and 创建一个数组 对象 Predicate new Predicate[0]作用 数组泛型类型
				Predicate[] predicates = accordingList.toArray(new Predicate[0]);
				return cb.and(predicates);// 5个条件 都是and
			}
		};
		return specification;
	}

}
